package system.schedule;

import java.util.ArrayList;
import java.util.List;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.apep.connect.APEPRequest;
import com.apep.connect.APEPResponse;
import com.apep.lib.xml.SampleElement;
import com.hitrust.gs.bean.GSProductSynConfigBean;
import com.hitrust.gs.dao.GSManufactureCategoryDAO;
import com.hitrust.gs.dao.GSManufactureDAO;
import com.hitrust.gs.dao.GSProductBidDao;
import com.hitrust.gs.dao.GSProductTypeDao;
import com.hitrust.gs.dao.GSProductTypeManagerDao;
import com.hitrust.gs.integration.socket.GSGwbsClient;
import com.hitrust.gs.lib.GSLogWriter;

public class ProductDownloadTask implements Job{

	private static boolean isRunning = false;
	public static String ROOT="data";
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		if(!isRunning){
			myRun();
		}else{
			System.out.println("-----------------------------");
		}	
	}

	private void myRun() {
		isRunning = true;
		try {
			GSManufactureDAO dao = new GSManufactureDAO();
			GSProductTypeManagerDao typeManagerDao=new GSProductTypeManagerDao();
			GSManufactureCategoryDAO categoryDao=new GSManufactureCategoryDAO();
			ArrayList list=dao.getProductSyncConfig();
				for(int i=0;i<list.size();i++){
					GSProductSynConfigBean bean=(GSProductSynConfigBean)list.get(i);
					SampleElement element=new SampleElement(ROOT);
					element.addChildElement(new SampleElement("id", String.valueOf(bean.getID())));
					element.addChildElement(new SampleElement("Table_name", bean.getTABLE_NAME()));
					element.addChildElement(new SampleElement("Last_Data_id", bean.getLAST_DATA_ID()));
					element.addChildElement(new SampleElement("Last_download_time", bean.getLAST_DOWNLOAD_TIME()));
					APEPRequest req=new APEPRequest();
					req.setAction("DownloadFromGwbs");
					req.setData(element);
					GSGwbsClient cilent=new GSGwbsClient();
					APEPResponse res= cilent.sendToGwbs(req);
					
					List dataList = res.getDataElementsList(bean.getTABLE_NAME());
					for(int j=0;j<dataList.size();j++){
						SampleElement se=(SampleElement)dataList.get(j);
						if("t_product_type_manager".equals(bean.getTABLE_NAME().toLowerCase().trim())){
							boolean flag=typeManagerDao.findProductTypeManagerById(se.getChildElement("id").getTagValue().trim());
							if(!flag){
								dao.insertProductTypeManager(se);
							}
						}else if("t_product_category".equals(bean.getTABLE_NAME().toLowerCase().trim())){
							boolean flag2=categoryDao.findManufatureCategoryById(se.getChildElement("id").getTagValue().trim());
							if(!flag2){
								dao.insertProductCategory(se);
							}
						}
					}
					GSLogWriter.info(res.toXml());
				}
		} catch (Exception e) {
			e.printStackTrace();
		}

		isRunning = false;
	}
}
